<template>
    <div class="page-wrap">
        <div class="page-cont" v-loading="loading">
            <div style="background: #fff; padding: 0 24px 12px 24px">
                <a-page-header @back="handleBack">
                    <template #title>
                        <flexbox style="width: 100%">
                            <span>{{ reportName }} </span>
                            <flexbox justify="flex-end" style="flex: 1">
                                <a-button type="primary" class="margin-r-8" @click="handleSave" v-if="canSave">已阅</a-button>
                                <flexbox
                                    style="font-size: 14px"
                                    @click.stop="handleDetail"
                                    v-if="canShowPreviewItem?.pmpProductDetailDTO"
                                    v-auth="'energyManage.analysisReport.beijixingBoard.preview'"
                                >
                                    <a style="margin-right: 6px">查看报告</a>
                                    <RightOutlined class="primary-color" />
                                </flexbox>
                            </flexbox>
                        </flexbox>
                    </template>
                </a-page-header>
                <flexbox>
                    <flexbox style="width: 20%" align="flex-start">
                        <flexbox justify="center" class="header-item-left" style="background: rgba(116, 115, 249, 0.1)">
                            <my-icon style="color: #7373f9; font-size: 16px" type="iconxitong" />
                        </flexbox>
                        <div class="margin-l-8" style="margin-top: -6px">
                            <span style="font-size: 30px; font-weight: bold">{{ headerInfo.systemReportCount }}</span>
                            <div class="margin-t-8" style="color: #8590a5">产品化信息管理系统</div>
                        </div>
                    </flexbox>
                    <flexbox style="width: 20%" align="flex-start">
                        <flexbox justify="center" class="header-item-left" style="background: rgba(254, 132, 94, 0.1)">
                            <my-icon style="color: #fe845e; font-size: 16px" type="iconyunyingguanli1" />
                        </flexbox>
                        <div class="margin-l-8" style="margin-top: -6px">
                            <span style="font-size: 30px; font-weight: bold"
                                >{{ headerInfo.insideSystemCount }}/{{ headerInfo.outsideSystemCount }}</span
                            >
                            <div class="margin-t-8" style="color: #8590a5">全生命周期管理/部分阶段管理</div>
                        </div>
                    </flexbox>
                    <flexbox style="width: 20%" align="flex-start">
                        <flexbox justify="center" class="header-item-left" style="background: rgba(63, 118, 252, 0.1)">
                            <my-icon style="color: #3f76fc; font-size: 16px" type="iconzhongtai" />
                        </flexbox>
                        <div class="margin-l-8" style="margin-top: -6px">
                            <span style="font-size: 30px; font-weight: bold"
                                >{{ headerInfo.insideSystemCount }}/{{ headerInfo.outsideSystemCount }}</span
                            >
                            <div class="margin-t-8" style="color: #8590a5">技术中台管理/JIRA管理</div>
                        </div>
                    </flexbox>
                    <flexbox style="width: 20%" align="flex-start">
                        <flexbox justify="center" class="header-item-left" style="background: rgba(254, 132, 94, 0.1)">
                            <my-icon style="color: #fe845e; font-size: 16px" type="iconfaban" />
                        </flexbox>
                        <div class="margin-l-8" style="margin-top: -6px">
                            <span style="font-size: 30px; font-weight: bold"
                                >{{ headerInfo.fixedReleaseCount }}/{{ headerInfo.unfixedReleaseCount }}</span
                            >
                            <div class="margin-t-8" style="color: #8590a5">固定发版/不固定发版</div>
                        </div>
                    </flexbox>
                    <flexbox style="width: 20%" align="flex-start">
                        <flexbox justify="center" class="header-item-left" style="background: rgba(253, 86, 95, 0.1)">
                            <my-icon style="color: #fd565f; font-size: 16px" type="iconyunyingguanli1" />
                        </flexbox>
                        <div class="margin-l-8" style="margin-top: -6px">
                            <span style="font-size: 30px; font-weight: bold"
                                >{{ headerInfo.independentCount }}/{{ headerInfo.purchaseCount }}/{{ headerInfo.mixCount }}</span
                            >
                            <div class="margin-t-8" style="color: #8590a5">自主研发/外包建设/混合</div>
                        </div>
                    </flexbox>
                </flexbox>
                <a-divider style="margin: 12px 0" />
                <div v-if="treeData && activeKey !== 'L9'">
                    <flexbox>
                        <span>产线/产品：</span>
                        <SelectCatalogCode v-model:value="catalogCode" :defaultTreeData="treeData" @change="handleCascaderChange" />
                    </flexbox>
                    <!-- <a-divider style="margin: 12px 0" /> -->
                </div>
            </div>
            <div class="margin-t-16" style="background: #fff; padding: 8px 24px 24px 24px; min-height: calc(100vh - 280px)">
                <a-tabs v-model:activeKey="activeKey" @change="handleTabChange" v-if="gradeTabList.length">
                    <a-tab-pane :key="item" :tab="item === 'L9' ? '本期无需求' : item" v-for="item of gradeTabList"></a-tab-pane>
                </a-tabs>
                <div v-if="activeKey === 'L9'">
                    <div style="padding: 10px 12px">下列产品本期无需求新增和版本变更</div>
                    <div style="background: #fff" v-if="treeData">
                        <a-card :title="key" v-for="key of Object.keys(treeData)" :bodyStyle="{ padding: 0 }" :key="key" :bordered="false">
                            <a-collapse accordion expandIconPosition="right">
                                <a-collapse-panel
                                    v-for="item of treeData[key]"
                                    :key="item.Id"
                                    :disabled="!(item.subNodes && item.subNodes.length)"
                                    :show-arrow="!!(item.subNodes && item.subNodes.length)"
                                >
                                    <template #header>
                                        <flexbox>
                                            <a-tag :color="item.node.catalogType === '1' ? 'green' : ''">{{
                                                $filters.catalogTypeFilter(item.node.catalogType)
                                            }}</a-tag>
                                            <span>{{ item.node.catalogName }}</span>
                                        </flexbox>
                                    </template>
                                    <div v-if="item.subNodes && item.subNodes.length">
                                        <flexbox v-for="elem of item.subNodes" :key="elem.id">
                                            <a-tag :color="elem.node.catalogType === '1' ? 'green' : ''">{{
                                                $filters.catalogTypeFilter(elem.node.catalogType)
                                            }}</a-tag>
                                            <span>{{ elem.node.catalogName }}</span>
                                        </flexbox>
                                    </div>
                                </a-collapse-panel>
                            </a-collapse>
                        </a-card>
                    </div>
                </div>
                <div v-else>
                    <div class="margin-t-16" style="background: #fff; min-height: calc(100vh - 270px)">
                        <div v-if="lineOptions.length">
                            <flexbox align="flex-start">
                                <div style="flex: 1">
                                    <flexbox align="flex-start">
                                        <div style="width: 60px; padding-top: 2px">产品线：</div>
                                        <div style="flex: 1">
                                            <flexbox wrap="wrap">
                                                <a-checkable-tag
                                                    :checked="checkedLine === index"
                                                    v-for="(item, index) of lineOptions"
                                                    :key="index"
                                                    @change="handleChangeLine($event, index)"
                                                    style="margin-bottom: 8px"
                                                >
                                                    {{ item.catalogName }}
                                                </a-checkable-tag>
                                            </flexbox>
                                        </div>
                                    </flexbox>

                                    <flexbox align="flex-start" class="margin-t-8">
                                        <div style="width: 60px; padding-top: 2px">产品：</div>
                                        <div style="flex: 1">
                                            <flexbox wrap="wrap">
                                                <a-checkable-tag
                                                    :checked="checkedPro === index"
                                                    v-for="(item, index) of proOptions"
                                                    :key="index"
                                                    @change="handleChangePro($event, index)"
                                                    style="margin-bottom: 8px"
                                                >
                                                    {{ item.catalogName }}
                                                </a-checkable-tag>
                                            </flexbox>
                                        </div>
                                    </flexbox>
                                </div>
                                <div style="width: 160px; font-weight: bold; font-size: 15px">
                                    <SwapOutlined class="primary-color" />
                                    <a class="margin-l-8" @click="handleChangeShowType">{{
                                        showBeijixing ? '切换到产线报告视角' : '切换到北极星视角'
                                    }}</a>
                                </div>
                            </flexbox>

                            <!-- <a-button-group size="small" class="margin-t-8">
                                <a-button @click="handleModeSwitch" :type="modeType === '1' ? 'primary' : 'default'">
                                    <UnorderedListOutlined />
                                </a-button>
                                <a-button @click="handleModeSwitch" :type="modeType === '2' ? 'primary' : 'default'">
                                    <TableOutlined />
                                </a-button>
                            </a-button-group>

                            <div v-if="modeType === '1'"></div>
                            <div v-else>
                                <CardList :list="list" :searchQuery="searchQuery" :queryArr="queryArr" :reportName="reportName" :reportType="reportType" @getItemData="getItemData" v-if="showBeijixing" />
                                <PreviewList :list="list" :searchQuery="searchQuery" :queryArr="queryArr" :reportName="reportName" :reportType="reportType" v-else />
                            </div> -->
                            <CardList
                                :list="list"
                                :searchQuery="searchQuery"
                                :queryArr="queryArr"
                                :reportName="reportName"
                                :reportType="reportType"
                                @getItemData="getItemData"
                                v-if="showBeijixing"
                            />
                            <PreviewList
                                :list="list"
                                :searchQuery="searchQuery"
                                :queryArr="queryArr"
                                :reportName="reportName"
                                :reportType="reportType"
                                v-else
                            />
                        </div>

                        <flexbox justify="center" style="background: #fff; min-height: calc(100vh - 400px)" v-if="isEmpty">
                            <a-empty />
                        </flexbox>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { treeFilter } from '@/utils/tree';
import api from '@/api';
import { SelectCatalogCode } from '@/components';
import { deepClone } from '@/utils/util';
import store from '@/store';
import { message } from 'ant-design-vue';
import filters from '@/utils/filter';
import CardList from '@/views/energyManage/analysisReport/beijixingBoard/pc/components/CardList.vue';
import PreviewList from '@/views/energyManage/analysisReport/beijixingBoard/pc/components/PreviewList/index.vue';
import { useRouterApi } from '@/hooks/common/useRouterApi';
import { RightOutlined, SwapOutlined, UnorderedListOutlined, TableOutlined } from '@ant-design/icons-vue';
import { defineComponent, reactive, toRefs, computed } from 'vue';

export default defineComponent({
    name: 'energyManageBeijixing',
    components: {
        CardList,
        PreviewList,
        RightOutlined,
        SwapOutlined,
        SelectCatalogCode,
        UnorderedListOutlined,
        TableOutlined
    },
    setup() {
        const { router, route, handleBack } = useRouterApi({
            backQuery: {
                path: '/setting'
            }
        });
        const state = reactive<any>({
            checkedLine: 0,
            checkedPro: -1,
            lineOptions: [],
            proOptions: [],
            treeData: null,
            searchQuery: {
                startTime: null,
                endTime: null,
                deliveryMode: null,
                isRequireAnalyse: '否'
            },
            list: [],
            loading: false,
            queryArr: [],
            reportName: '',
            reportType: null,
            headerInfo: {},
            isEmpty: false,
            canShowPreviewItem: {},
            showBeijixing: false,
            gradeTabList: [],
            activeKey: null,
            catalogCode: '',
            modeType: '2'
        });
        const canSave = computed(() => {
            const res = state.headerInfo.pushEmpId && state.headerInfo.pushEmpId.indexOf(store.getters.userInfo.employeeDTO.empId) >= 0;
            if (state.headerInfo.readEmpId) {
                return res ? state.headerInfo.readEmpId.indexOf(store.getters.userInfo.employeeDTO.empId) < 0 : false;
            } else {
                return res;
            }
        });
        const handleChangeLine = (val, index) => {
            if (val) {
                state.checkedLine = index;
                getProOptions([state.treeData[index]]);
            }
        };
        const handleChangePro = (val, index) => {
            if (val) {
                state.checkedPro = index;
                getList();
            }
        };
        // 查询所有数据
        const getList = async () => {
            if (state.checkedPro === 0) {
                state.catalogCode = state.lineOptions[state.checkedLine].catalogCode;
            } else {
                state.catalogCode = state.proOptions[state.checkedPro].catalogCode;
            }
            state.list = [];
            if (state.showBeijixing) {
                getBeijixingList();
            } else {
                getPreviewList();
            }
        };
        const getPreviewList = async () => {
            let codeStr = '';
            state.loading = true;
            // 点击全部
            if (state.checkedPro === 0) {
                state.proOptions.slice(1).forEach((item) => {
                    if (item.subNodes && item.subNodes.length) {
                        const subNodesStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                        if (codeStr) {
                            codeStr = `${codeStr},${item.catalogCode},${subNodesStr}`;
                        } else {
                            codeStr = `${item.catalogCode},${subNodesStr}`;
                        }
                    } else {
                        if (codeStr) {
                            codeStr = `${codeStr},${item.catalogCode}`;
                        } else {
                            codeStr = `${item.catalogCode}`;
                        }
                    }
                });
            }
            // 不是全部，点击某个产品，1.传自身产品code 2.有子产品的，遍历所有子产品的code
            else {
                const item = state.proOptions[state.checkedPro];
                if (item.subNodes && item.subNodes.length) {
                    const subNodesStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                    codeStr = `${item.catalogCode},${subNodesStr}`;
                } else {
                    codeStr = item.catalogCode;
                }
            }
            const query = {
                id: route.query.id,
                catalogCode: codeStr
            };
            const { success, moule, errorMsg } = await api.systemReportModel.getSystemReportInfos(query);
            if (success) {
                state.list = [...moule];
                state.canShowPreviewItem = state.list.find(
                    (item) => (item.pmpProductDetailDTO.isSettingReport =
                            1 &&
                            ((state.reportType == 1 && item.pmpProductDetailDTO.isMonth == 1) ||
                                (state.reportType == 2 && item.pmpProductDetailDTO.isQuarter == 1) ||
                                (state.reportType == 3 && item.pmpProductDetailDTO.isHalfYear == 1) ||
                                (state.reportType == 4 && item.pmpProductDetailDTO.isYear == 1)))
                );
            } else {
                message.error(errorMsg);
            }
            state.loading = false;
        };
        const getBeijixingList = async () => {
            state.loading = true;
            if (state.checkedPro === 0) {
                // 如果是全部，参数有两种情况：1 有子产品的传递子产品code拼接成的字符串 2.没有子产品的传递自身的code
                state.queryArr = state.proOptions.slice(1).map((item) => {
                    if (item.subNodes && item.subNodes.length) {
                        const codeStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                        return {
                            catalogCode: `${item.catalogCode},${codeStr}`,
                            catalogType: '1'
                        };
                    } else {
                        return {
                            catalogCode: item.catalogCode,
                            catalogType: '1'
                        };
                    }
                });
            }
            // 不是全部，点击某个产品，1.传自身产品code 2.有子产品的，遍历所有子产品的code
            else {
                const item = state.proOptions[state.checkedPro];
                if (item.subNodes && item.subNodes.length) {
                    const codeArr = item.subNodes.map((item) => ({
                        catalogCode: item.node.catalogCode,
                        catalogType: '2'
                    }));
                    const codeStr = item.subNodes.map((item) => item.node.catalogCode).join(',');
                    state.queryArr = [
                        {
                            catalogType: '1',
                            catalogCode: `${item.catalogCode},${codeStr}`
                        },
                        ...codeArr
                    ];
                } else {
                    state.queryArr = [
                        {
                            catalogType: '1',
                            catalogCode: item.catalogCode
                        }
                    ];
                }
            }
            let allRequestAArr = [];
            let allRequestBArr = [];
            if (state.proOptions.length) {
                allRequestAArr = state.queryArr.map(
                    async (item) => await api.portalControlModel.getPolarisIndexBoard({
                        ...state.searchQuery,
                        catalogCode: item.catalogCode,
                        catalogType: item.catalogType
                    })
                );
                allRequestBArr = state.queryArr.map(
                    async (item) => await api.portalControlModel.getQualityBoar({
                        ...state.searchQuery,
                        catalogCode: item.catalogCode,
                        catalogType: item.catalogType
                    })
                );
                const list: any = [];
                const resA = await Promise.allSettled(allRequestAArr);
                resA.forEach((item: any) => {
                    const { success, moule } = item.value;
                    if (success) {
                        if (moule.pmpProductDetailDTO.isOutsideSystem === '0') {
                            list.push({
                                isRequireAnalyse: '否',
                                deliveryMode: null,
                                ...moule
                            });
                        } else {
                            list.push(moule);
                        }
                    }
                });
                const resB = await Promise.allSettled(allRequestBArr);
                resB.forEach((item: any, index) => {
                    const { success, moule } = item.value;
                    if (success) {
                        if (moule) {
                            list[index] = {
                                ...list[index],
                                ...moule
                            };
                        }
                    }
                });
                state.loading = false;
                state.list = [...list];
                state.canShowPreviewItem = state.list.find(
                    (item) => (item.pmpProductDetailDTO.isSettingReport =
                            1 &&
                            ((state.reportType == 1 && item.pmpProductDetailDTO.isMonth == 1) ||
                                (state.reportType == 2 && item.pmpProductDetailDTO.isQuarter == 1) ||
                                (state.reportType == 3 && item.pmpProductDetailDTO.isHalfYear == 1) ||
                                (state.reportType == 4 && item.pmpProductDetailDTO.isYear == 1)))
                );
            }
        };
        // 请求某个外采数据
        const getItemData = async ({ index, item }) => {
            const { success, moule } = await api.portalControlModel.getPolarisIndexBoard({
                ...state.searchQuery,
                catalogCode: state.queryArr[index].catalogCode,
                catalogType: state.queryArr[index].catalogType,
                isRequireAnalyse: item.isRequireAnalyse,
                deliveryMode: item.deliveryMode
            });
            if (success) {
                state.list[index] = { ...state.list[index], ...moule, isRequireAnalyse: item.isRequireAnalyse, deliveryMode: item.deliveryMode };
            }
        };

        const getAllProItem = (treeData) => {
            const arr: any = [];
            const getItem = (data) => {
                data.forEach((item) => {
                    if (item.node.catalogType === '0') {
                        if (item.subNodes && item.subNodes.length) {
                            getItem(item.subNodes);
                        }
                    } else {
                        if (item.node.catalogType === '1') {
                            arr.push({
                                id: item.id,
                                ...item.node,
                                node: item.node,
                                subNodes: item.subNodes || []
                            });
                        }
                    }
                });
            };
            getItem(treeData);
            return arr;
        };
        const getProOptions = (treeData) => {
            state.proOptions = getAllProItem(treeData);
            if (state.proOptions.length) {
                state.proOptions.unshift({
                    catalogName: '全部'
                });
                state.checkedPro = 0;
                getList();
            }
        };
        const getSystemStatistics = async () => {
            const { moule, success } = await api.systemReportModel.getSystemStatistics({
                id: route.query.id
            });
            if (success) {
                state.reportName = moule.reportName;
                const { startTime, endTime } = filters.reportTimeRangeFilter(moule.reportName, moule.reportType);
                state.searchQuery.startTime = startTime;
                state.searchQuery.endTime = endTime;
                state.headerInfo = {
                    ...moule
                };
                state.reportType = moule.reportType;
            }
            return success;
        };

        const handleSave = async () => {
            const query = {
                id: route.query.id,
                readEmpId: store.getters.userInfo.employeeDTO.empId
            };
            const { success, errorMsg } = await api.requireReportModel.leaderSave(query);
            if (success) {
                message.success('操作成功');
                router.push({
                    path: '/energyManage/analysisReport'
                });
            } else {
                message.error(errorMsg);
            }
        };

        const handleDetail = () => {
            if (state.canShowPreviewItem.pmpProductDetailDTO) {
                router.push({
                    path: '/energyManage/analysisReport/preview',
                    query: {
                        id: route.query.id,
                        catalogCode: state.canShowPreviewItem.pmpProductDetailDTO.catalogCode,
                        startTime: state.searchQuery.startTime,
                        endTime: state.searchQuery.endTime,
                        reportName: state.reportName
                    }
                });
            }
        };

        const handleChangeShowType = () => {
            state.showBeijixing = !state.showBeijixing;
            getList();
        };
        const handleTabChange = (val) => {
            state.treeData = null;
            getPBITreeData();
        };
        const getReportPBIProductGrade = async () => {
            const query = {
                id: route.query.id
            };
            const { success, moule } = await api.requireReportModel.getReportPBIProductGrade(query);
            if (success) {
                if (moule[0]) {
                    state.gradeTabList = moule.filter((item) => item);
                    state.activeKey = moule[0];
                } else {
                    state.gradeTabList = [];
                    state.activeKey = null;
                }
            }
        };
        const initOptions = async (catalogCode = '', catalogType = '') => {
            // 获取产品选项
            if (catalogCode && catalogType) {
                const target: any = treeFilter(state.treeData, (node) => node.node.catalogCode === catalogCode);
                console.log('target', target);
                if (target && target.length) {
                    const lineIndex = state.treeData.findIndex((item) => item.node.catalogCode === target[0].node.catalogCode);
                    state.checkedLine = lineIndex;
                    state.proOptions = getAllProItem([state.treeData[lineIndex]]);
                    if (state.proOptions.length) {
                        state.proOptions.unshift({
                            catalogName: '全部'
                        });
                    }
                    const proIndex = state.proOptions.findIndex((item) => item.node ? item.node.catalogCode === target[0].subNodes[0].node.catalogCode : false
                    );
                    state.checkedPro = proIndex;
                    getList();
                } else {
                    getProOptions([state.treeData[0]]);
                }
            } else {
                const res = await getSystemStatistics();
                if (res) {
                    getProOptions([state.treeData[0]]);
                }
            }
        };
        const getPBITreeData = async () => {
            state.isEmpty = false;
            const { success, moule } = await api.systemReportModel.getReportPBITreeData({
                id: route.query.id,
                productGrade: state.activeKey
            });
            if (success) {
                if (moule) {
                    if (state.activeKey === 'L9') {
                        const obj = JSON.parse(moule);
                        Object.keys(obj).forEach((key) => {
                            const item = JSON.parse(obj[key]);
                            obj[key] = [];
                            item.forEach((elem) => obj[key].push(...elem.subNodes));
                        });
                        state.treeData = deepClone(obj);
                    } else {
                        state.treeData = JSON.parse(moule);
                        state.lineOptions = state.treeData.map((item) => ({
                            id: item.id,
                            ...item.node
                        }));
                        if (state.lineOptions.length) {
                            initOptions();
                        }
                    }
                } else {
                    state.isEmpty = true;
                }
            }
        };
        const handleCascaderChange = (val) => {
            const { nodeInfo } = val;
            initOptions(nodeInfo.catalogCode, nodeInfo.catalogType);
        };
        const handleModeSwitch = () => {
            state.modeType = state.modeType === '1' ? '2' : '1';
        };
        const init = async () => {
            await getReportPBIProductGrade();
            getPBITreeData();
        };
        init();
        return {
            ...toRefs(state),
            handleChangeLine,
            handleChangePro,
            getItemData,
            handleBack,
            canSave,
            handleSave,
            handleDetail,
            handleChangeShowType,
            handleTabChange,
            handleCascaderChange,
            handleModeSwitch
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.ant-form-item-label) {
    text-align: left;
}
.page-wrap {
    .page-cont {
        ::v-deep(.ant-page-header) {
            border-bottom: none !important;
            padding: 16px 24px 16px 0;
        }
        ::v-deep(.ant-page-header-heading) {
            width: 100%;
        }
        ::v-deep(.ant-page-header-heading) {
            width: 100%;
        }
        ::v-deep(.ant-page-header-heading-left) {
            width: 100%;
        }
        ::v-deep(.ant-page-header-heading-title) {
            width: 100%;
        }
        .header-item-left {
            width: 32px;
            height: 32px;
            border-radius: 18px;
        }
        ::v-deep(.ant-tabs-top-bar) {
            margin: 0 !important;
        }
    }
}
</style>